<?php

namespace app\models\product;

use app\models\constant\Status;
use app\models\Images;
use Yii;

/**
 * This is the model class for table "product_sku".
 *
 * @property int $id
 * @property int $product_id 商品
 * @property float $price 价格
 * @property string $image_id 图片
 * @property int $stock 库存
 * @property int $status 1开 0关 -99删除
 * @property int $sort
 * @property string $sku_list sku value, json数组, 如: "[1, 2, 4]"
 * @property float $self_cost 成本
 * @property string $create_time
 * @property string $update_time
 */
class ProductSku extends \yii\db\ActiveRecord
{
    use Status;

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'product_sku';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['product_id', 'stock', 'status', 'sort', 'image_id'], 'integer'],
            [['price', 'self_cost'], 'number'],
            [['create_time', 'update_time'], 'safe'],
            // [['sku_list'], 'string', 'max' => 255],
            [['sku_list'], 'safe'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'product_id' => 'Product ID',
            'price' => 'Price',
            'image_id' => 'Image ID',
            'stock' => 'Stock',
            'status' => 'Status',
            'sort' => 'Sort',
            'sku_list' => 'Sku List',
            'self_cost' => 'Self Cost',
            'create_time' => 'Create Time',
            'update_time' => 'Update Time',
        ];
    }

    /**
     * Save timestamp
     * @param bool $insert
     * @return bool
     */
    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            $time = date('Y-m-d H:i:s');
            $this->update_time = $time;
            if ($insert) {
                $this->create_time = $time;
            }
            return true;
        }
        return false;
    }

    public function getImage()
    {
        return $this->hasOne(Images::class, ['id' => 'image_id']);
    }

    public static function skuList($sku_list)
    {
        $list = explode('|', $sku_list);
        $values = ProductSkuValue::find()
            ->where(['id' => $list])
            ->select(['value'])
            ->column();

        return $values;
    }

    public static function skuValue($sku_list)
    {
        return explode('|', $sku_list);
    }
}
